<template>
  <div class="problem">
    <Steps :active-step="1" />
    <div id="gen-pdf" v-loading.fullscreen.lock="genPdf">
      <c-section title="门店验收基本信息">
        <template v-slot:right>
          <c-abnormal-preview gen-pdf="gen-pdf-hide" path="/storeConstruction/exceptionManage" :query="{ constCode: detail.constCode, functionModel: 'SHOP_DECORATION' }" />
        </template>
        <c-list ref="form" :column="3" :model="formData" :rules="formRules" label-width="135px">
          <c-list-item label="门店编码" :value="detail.shopCode" />
          <c-list-item label="门店" :value="detail.shopName" />
          <c-list-item label="所属客户编码" :value="detail.clientCode" />
          <c-list-item label="所属客户" :value="detail.clientName" />
          <c-list-item label="所属办事处" :value="detail.officeName" />
          <c-list-item label="门店类型" dict-type-code="SHOP_TYPE" :value="detail.shopType" />
          <c-list-item label="门店业务类型" dict-type-code="BIZ_TYPE" :value="detail.shopBizType" />
          <c-list-item label="门店城市级别" dict-type-code="CITY_LEVEL" :value="detail.shopCityLevel" />
          <c-list-item label="门店详细地址" :value="detail.shopAddress" :span="3" />
          <c-list-item label="门店建设项目号" :value="detail.constCode" />
          <c-list-item label="报图类型" dict-type-code="MARKET_TYPE" :value="detail.marketType" />
          <c-list-item label="门店建设类型" dict-type-code="CONST_TYPE" :value="detail.constType" />
          <c-list-item label="商家类别" dict-type-code="BIZMAN_TYPE" :value="detail.bizmanType" />
          <c-list-item label="装修形式" dict-type-code="DECORATION_FORM" :value="detail.decorationFormCal || detail.decorationForm" />
          <c-list-item label="门店建设范围" dict-type-code="DECORATION_RANGE" :value="detail.decorationRange" />
          <c-list-item label="本次装修范围" dict-type-code="DECORATION_RANGE" :value="detail.range" />
          <!-- <c-list-item label="预计报验时间" :value="detail.expectInspectionTime" /> -->
          <c-list-item label="验收类型" dict-type-code="ACCEPT_TYPE" :value="detail.acceptType" />
          <c-list-item label="报验申请人" :value="detail.applyInformantName" />
          <c-list-item label="工程监理" :value="detail.proSupervisorName" />
          <c-list-item label="形象督导" :value="detail.formSupervisorName" />
          <c-list-item label="施工单位" :value="detail.constUnitName" />
          <c-list-item label="报验申请时间" :value="detail.applyReportTime" />
          <c-list-item v-if="!genPdf" label="实际验收时间" prop="actualAcceptTime">
            <el-date-picker
              v-model="formData.actualAcceptTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            />
          </c-list-item>
          <c-list-item v-else label="实际验收时间" :value="formData.actualAcceptTime" />
          <c-list-item label="设计完成时间" :value="detail.completeTime" />
          <c-list-item label="验收人员" :value="detail.accepterName" />
          <c-list-item v-if="!genPdf" label="验收卖场总面积(㎡)" prop="acceptShopTotalArea" suffix="m²" value="">
            <el-input v-model="formData.acceptShopTotalArea" placeholder="验收卖场总面积" clearable />
          </c-list-item>
          <c-list-item v-else label="验收卖场总面积(㎡)" :value="detail.acceptShopTotalArea" />

          <c-list-item v-if="!genPdf" label="验收门头总面积(㎡)" prop="acceptDheadTotalArea" suffix="m²" value="">
            <el-input v-model="formData.acceptDheadTotalArea" placeholder="验收门头总面积" clearable />
          </c-list-item>
          <c-list-item v-else label="验收门头总面积(㎡)" :value="detail.acceptDheadTotalArea" />

          <!-- <c-list-item label="非本次验收区域总面积" suffix="m²" :value="detail.nonAcceptanceTotalArea || 0" /> -->
          <c-list-item label="非本次验收门头总面积" suffix="m²" :value="detail.unAccDheadArea || 0" />
          <c-list-item label="非本次验收卖场总面积" suffix="m²" :value="detail.unAccShopArea || 0" />
          <c-list-item v-if="!genPdf" label="本次装修业务类型" prop="decorationBizType" value="">
            <el-select
              v-model="decorationBizTypeArr"
              multiple
              placeholder="请选择"
              @change="changeDecorationBizType"
            >
              <el-option
                v-for="item in shopBizTypeOptions"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </c-list-item>
          <c-list-item v-else label="本次装修业务类型" dict-type-code="DECORATION_BIZ_TYPE" label-width="140px" :span="2" :value="formData.decorationBizType" />

          <c-list-item v-if="!genPdf" label="验收面积汇总说明" label-width="140px" :span="3" prop="areaSummaryDesc">
            <el-input v-model="formData.areaSummaryDesc" type="textarea" maxlength="1024" show-word-limit :autosize="{minRows: 3}" placeholder="验收面积汇总说明" clearable />
          </c-list-item>
          <c-list-item v-else label="验收面积汇总说明" label-width="140px" :span="3" :value="formData.areaSummaryDesc" />

          <c-list-item v-if="!genPdf" label="门楣核算" label-width="140px" :span="3" prop="lintelAccounting">
            <el-input v-model="formData.lintelAccounting" type="textarea" maxlength="1024" :autosize="{minRows: 2}" show-word-limit placeholder="门楣核算" clearable />
          </c-list-item>
          <c-list-item v-else label="门楣核算" label-width="140px" :span="3" :value="formData.lintelAccounting" />

          <c-list-item label="异常申请核实结果" label-width="140px" :span="3" prop="exceptionVerifyResult">
            <el-input v-model="formData.exceptionVerifyResult" type="textarea" maxlength="2048" :autosize="{minRows: 2}" show-word-limit placeholder="异常申请核实结果" clearable />
          </c-list-item>

          <c-list-item label="验收项目专员" :value="detail.accepterName" />
          <c-list-item :rules="[{ required: true, message:account.length>0 ?'请选择客户经理':'所属客户下未配置业务账号,没有选择数据', trigger: 'change' }]" label="客户经理" prop="clientManagerCode">
            <c-single-dialog
              ref="clientManagerCode"
              v-model="formData.clientManagerCode"
              :label.sync="formData.clientManagerName"
              :props="{label:'name',value:'adAccount'}"
              :disabled="account.length===0"
              :focus-query="true"
              :multiple="false"
              :config="{
                title:'客户经理',
                width:'600px',
                interfacePath: '/slm-admin/api/v1/user/listCustomerManagerByAccounts',
                method:'post',
                paramField:'',
                filtersRaw:filtersRaw,
                paramsRaw:{},
                setting:[
                  {prop:'adAccount',title:'编码',width:80},
                  {prop:'name',title:'名称',width:200},
                  {prop:'tel',title:'电话',width:200}
                ]
              }"
            />
          </c-list-item>
          <c-list-item v-if="!genPdf" label="验收整装总面积" prop="acceptWholeTotalArea" label-width="140px">
            <c-input-number v-model="formData.acceptWholeTotalArea" float placeholder="验收整装总面积" clearable />
          </c-list-item>

          <c-list-item v-else label="验收整装总面积" suffix="m²" :value="formData.acceptWholeTotalArea" label-width="140px" />

          <c-list-item v-if="!genPdf" label="验收简装总面积" prop="acceptSimpleTotalArea" label-width="140px">
            <c-input-number v-model="formData.acceptSimpleTotalArea" float placeholder="验收简装总面积" clearable />
          </c-list-item>
          <c-list-item v-else label="验收简装总面积" suffix="m²" :value="formData.acceptSimpleTotalArea" label-width="140px" />
          <!-- <c-list-item v-if="!genPdf" :span="3" label="备注123" prop="remark">
            <el-input v-model="formData.remark" maxlength="1000" show-word-limit type="textarea" placeholder="请填写备注" />
          </c-list-item>
          <c-list-item v-else :span="3" label="备注2" :value="formData.remark" /> -->
        </c-list>
      </c-section>
      <c-section title="验收问题明细">
        <c-permission-tabs :lazy="false">
          <el-tab-pane v-if="acceptType.includes('HARD')" label="硬装验收结果" name="hard">
            <ProblemDetail ref="hard" :range="detail.range" acc-type="hard" type="hard" show-btn @save="printSave" @gen-pdf="genPdfHandle" />
          </el-tab-pane>
          <el-tab-pane v-if="acceptType.includes('SOFT')&&!genPdf" label="软装验收结果" name="soft">
            <ProblemDetail ref="soft" :range="detail.range" acc-type="hard" type="soft" @save="printSave" @gen-pdf="genPdfHandle" />
          </el-tab-pane>
        </c-permission-tabs>
        <c-permission-tabs v-show="acceptType.includes('SOFT')&&genPdf" :lazy="false">
          <el-tab-pane label="软装验收结果" name="soft">
            <ProblemDetail :range="detail.range" :data="softTableData" acc-type="hard" type="soft" @save="printSave" />
          </el-tab-pane>
        </c-permission-tabs>
      </c-section>
    </div>
    <c-section style="padding-bottom:50px" title="验收附件">
      <c-file-table-box v-model="files" title="上传附件" belong-model="HARD_REPORT" :model-id="$route.query.id" />
    </c-section>
    <div class="footer-btn">
      <c-button type="primary" @click="clickPrevStep">上一步</c-button>
      <c-button type="primary" @click="saveHandle">保存</c-button>
      <c-button v-if="detail.haveFrock==='1' || detail.haveFrock === 1" type="primary" @click="clickNextStep">下一步</c-button>
      <c-button v-else type="primary" @click="commitHandle">提交</c-button>
    </div>
  </div>
</template>
<script>
import { searchDesignTime } from '@/api/common'
import { otherFiltersItem } from '@/utils'
import Steps from './components/steps'
import ProblemDetail from '../../components/problemDetail'
import { getDictByPatchType } from '@/api/dataDict'

import { getApplyDetail, postSaveProblem, getCustomerCode, postAccountPage } from '@/api/check'
export default {
  name: 'CheckHardExecuteProblem',
  components: {
    Steps,
    ProblemDetail
  },
  data() {
    return {
      shopBizTypeOptions: [],
      customerCode: '',
      acceptType: '',
      detail: {},
      genPdf: false,
      account: [],
      summaryDescSelfDefine: '',
      decorationBizTypeArr: [],
      formData: {
        actualAcceptTime: '',
        areaSummaryDesc: '',
        decorationBizType: '', // 本次装修业务类型
        acceptDheadTotalArea: '',
        acceptShopTotalArea: '',
        clientManagerName: '',
        clientManagerCode: '',
        acceptWholeTotalArea: '',
        acceptSimpleTotalArea: '',
        remark: '',
        lintelAccounting: '',
        exceptionVerifyResult: ''
      },
      formRules: {
        actualAcceptTime: [{ required: true, message: '请选择实际验收时间', trigger: 'change' }],
        areaSummaryDesc: [{ required: true, message: '请输入验收面积汇总说明', trigger: 'change' }],
        decorationBizType: [{ required: true, message: '请选择', trigger: 'change' }],
        acceptWholeTotalArea: [{ required: true, message: '请输入验收整装总面积', trigger: 'change' }],
        clientManagerCode: [{ required: true, message: '请选择客户经理', trigger: 'change' }],
        acceptSimpleTotalArea: [{ required: true, message: '请输入验收简装总面积', trigger: 'change' }]
      },
      files: [],
      selectionFiles: [],
      softTableData: []
    }
  },
  computed: {
    filtersRaw() {
      return [otherFiltersItem('accounts', `${this.account.join(',')}`, 'in')] // 没有错，不加[]
    }
  },
  async  created() {
    this.getDetail()
    const { DECORATION_BIZ_TYPE } = await getDictByPatchType(['DECORATION_BIZ_TYPE'])
    this.shopBizTypeOptions = DECORATION_BIZ_TYPE // 门店建设整体进度

    // this.getFilesConfig()
  },
  methods: {
    changeDecorationBizType(data) {
      this.formData.decorationBizType = data.join(',')
    },
    async getCustomerCode() {
      if (this.detail.clientCode) {
        this.customerCode = this.detail.clientCode
      } else {
        await getCustomerCode(this.detail.shopCode).then(customerCode => {
          this.customerCode = customerCode
        })
      }
      return await postAccountPage(this.customerCode).then(res => {
        this.account = res.data.records.map(e => e.code)
        if (!this.account || this.account.length === 0) this.$message.warning('业务账号未配置,不能报验数据')
      })
    },
    printSave(type) {
      return this.$refs.form.validate().then(() => {
        const p1 = this.$refs.hard ? this.$refs.hard.genData() : Promise.resolve([])
        const p2 = this.$refs.soft ? this.$refs.soft.genData() : Promise.resolve([])
        return Promise.all([p1, p2]).then(d => {
          const { id } = this.$route.query
          const hardAcceptDutyDTOList = d[0]
          const softAcceptDutyDTOList = d[1]
          const data = {
            id,
            ...this.formData,
            hardAcceptDutyDTOList,
            softAcceptDutyDTOList
          }
          return postSaveProblem(data, 'save').then(res => {
            const routeUrl = this.$router.resolve({
              path: '/printReport',
              query: { id: this.$route.query.id, type }
            })
            window.open(routeUrl.href, '_blank')
          })
        })
      })
    },
    clickPrevStep() {
      // this.$router.push({ name: 'CheckHardExecute', query: this.$route.query })
      this.$store.dispatch('views/goBack')
    },
    clickNextStep() {
      return this.saveData().then(() => {
        if (this.detail.acceptType === 'SOFT') {
          this.$router.push({ name: 'CheckHard' })
          return
        }
        this.$router.push({ name: 'CheckHardExecuteAssess', query: { ...this.$route.query, unitCode: this.detail.constUnitCode }})
      })
    },
    getDetail() {
      const { id } = this.$route.query

      getApplyDetail(id).then(res => {
        this.detail = res.data
        this.getCustomerCode()
        searchDesignTime(this.detail.constCode).then(res => {
          if (res.data.records.length > 0) {
            const data = res.data.records[0]
            this.$set(this.detail, 'completeTime', data.completeTime)
          }
        })

        this.acceptType = this.detail.acceptType
        for (const key of Object.keys(this.formData)) {
          this.$set(this.formData, key, this.detail[key])
        }
        this.decorationBizTypeArr = (this.formData.decorationBizType && this.formData.decorationBizType.split(',')) || []
      })
    },
    saveData(type = 'save') {
      return this.$refs.form.validate().then(() => {
        const p1 = this.$refs.hard ? this.$refs.hard.genData() : Promise.resolve([])
        const p2 = this.$refs.soft ? this.$refs.soft.genData() : Promise.resolve([])
        return Promise.all([p1, p2]).then(d => {
          const files = this.$getFiles(this.files, id)
          const _files = files.filter(e => e.dr !== '1' && e.dr !== 1)
          if (_files.length === 0) {
            this.$message.warning('至少上传一个附件！')
            return Promise.reject()
          }
          for (let i = 0; i < _files.length; i++) {
            const t = _files[i]
            if (!t.configAttachmentId) {
              this.$message.warning(`请选择第${i + 1}行附件类型！`)
              return Promise.reject()
            }
            if (t.attachmentName === '' || t.attachmentName === undefined) {
              this.$message.warning(`请填写第${i + 1}行附件名称！`)
              return Promise.reject()
            }
          }
          const { id } = this.$route.query
          const hardAcceptDutyDTOList = d[0]
          const softAcceptDutyDTOList = d[1]
          const data = {
            id,
            ...this.formData,
            hardAcceptDutyDTOList,
            softAcceptDutyDTOList,
            files
          }
          return postSaveProblem(data, type || 'save').then(res => {
            this.$message.success('操作成功！')
          })
        })
      })
    },
    saveHandle() {
      return this.saveData().then(() => {
        this.$store.dispatch('views/goFirst')
      })
    },
    commitHandle() {
      return this.saveData('commit').then(() => {
        this.$store.dispatch('views/goFirst')
      })
    },
    genPdfHandle(v) {
      this.genPdf = v
      this.softTableData = this.$refs.soft ? this.$refs.soft.tableData : []
    }
  }
}
</script>
<style lang="scss" scoped>
.problem{
  padding-top: 20px;
}
</style>
